package de.breitbeil.jbooking.ui.view;

import javax.swing.JComponent;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.richclient.application.event.LifecycleApplicationEvent;
import org.springframework.richclient.application.support.AbstractView;

import de.breitbeil.jbooking.dao.IGenericDao;
import de.breitbeil.jbooking.domain.Booking;
import de.breitbeil.jbooking.ui.components.YearBookingCalendar;

public class BookingCalendarView extends AbstractView implements ApplicationListener {

    public static String ID = "calendarView";
    
    private IGenericDao genericDao;
    private YearBookingCalendar calendar;
    
    public BookingCalendarView() {
    }
    
    public void setGenericDao(IGenericDao genericDao) {
        this.genericDao = genericDao;
    }
    
    @Override
    protected JComponent createControl() {
        if(calendar == null) {
            calendar = new YearBookingCalendar();
            calendar.setYearLabelText(getMessage("year.label"));
            
            for(Booking booking: genericDao.findAll(Booking.class)) {
                calendar.getMonthView().addBooking(booking);
            }
        }
        
        return getComponentFactory().createScrollPane(calendar);
    }
    
    
    /**
     * Handle an application event. This will notify us of object adds, deletes, and modifications. Forward to our
     * object table for handling.
     * @param e event to process
     */
    public void onApplicationEvent(ApplicationEvent e) {
        if (e instanceof LifecycleApplicationEvent && calendar != null) {
            LifecycleApplicationEvent le = (LifecycleApplicationEvent) e;
            if(le.getObject() instanceof Booking) {
                Booking booking = (Booking) le.getObject();
                
                if(le.getEventType().equals(LifecycleApplicationEvent.CREATED)) {
                    calendar.getMonthView().addBooking(booking);
                }
                else if(le.getEventType().equals(LifecycleApplicationEvent.DELETED)) {
                    calendar.getMonthView().removeBooking(booking);
                }
                else if(le.getEventType().equals(LifecycleApplicationEvent.MODIFIED)) {
                    calendar.getMonthView().removeBooking(booking);
                    calendar.getMonthView().addBooking(booking);
                }
            }
        }
    }
    
}
